package com.woquyin.utils;

import java.io.File;
import org.apache.commons.lang3.StringUtils;

import com.aliyun.oss.OSSClient;
import com.jfinal.kit.PropKit;
import com.woquyin.common.Constance;
import com.woquyin.vo.ReturnData;

public class OSSUtil {

	private final static String endpoint = PropKit.use("fileUpload.properties").get("endPoint");
	private final static String accessKeyId = PropKit.use("fileUpload.properties").get("accesskeyID");
	private final static String accessKeySecret = PropKit.use("fileUpload.properties").get("accesskeySecret");
	private final static String bucket = PropKit.use("fileUpload.properties").get("bucket");

	/**
	 * 上传文件
	 * 
	 */
	public static ReturnData<String> fileUpload(File file, String gon) {
		ReturnData<String> returnData = new ReturnData<String>();
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			String url = gon + file.getName();
			ossClient.putObject(bucket, url, file);
			url = "http://" + bucket + "." + endpoint + url;
			returnData.setData(url);
			returnData.setCode(Constance.WholeStateCodeEnum.SUCCESS.getCode());
		} catch (Exception e) {
			e.printStackTrace();
			returnData.setCode(Constance.WholeStateCodeEnum.OTHER_ERROR.getCode());
			returnData.setMsg(Constance.WholeStateCodeEnum.OTHER_ERROR.getValue());
		} finally {
			ossClient.shutdown();
		}
		return returnData;
	}

	/**
	 * 删除图片
	 */
	public static ReturnData<String> delFile(String fileName) {
		ReturnData<String> returnData = new ReturnData<String>();
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
		try {
			if (!StringUtils.isBlank(fileName) && fileName.indexOf("user.png")==-1) {
				ossClient.deleteObject(bucket, fileName);
				returnData.setCode(Constance.WholeStateCodeEnum.SUCCESS.getCode());
			}else{
				returnData.setCode(Constance.WholeStateCodeEnum.OTHER_ERROR.getCode());
				returnData.setMsg(Constance.WholeStateCodeEnum.OTHER_ERROR.getValue());
			}
		} catch (Exception e) {
			e.printStackTrace();
			returnData.setCode(Constance.WholeStateCodeEnum.OTHER_ERROR.getCode());
			returnData.setMsg(Constance.WholeStateCodeEnum.OTHER_ERROR.getValue());
		} finally {
			ossClient.shutdown();
		}
		return returnData;
	}

}
